/*
 *  Openmysee
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
				 
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <syslog.h>
#include <string.h>
#include <time.h>
#include <dirent.h>
#include <db.h>
#include "echo.h"
extern int db_init (char *home, char *database);
extern int db_add (int userid, char *pass, char *cname, float limited, int issave);
extern int db_list ();
extern int db_del (int userid);
extern int db_end ();

int
main (int argc, char **argv)
{
	int userid, i, ret;
	if (db_init (DB_DIR, "user.db") < 0)
	{
		fprintf (stderr, "Error in initial %s/user.db\n", DB_DIR);
		exit (1);
	}
	if (argc >= 7 && strcmp (argv[1], "-add") == 0)
	{
		userid = atoi (argv[2]);
		float bitrate = atof (argv[5]);
		int issave = atoi (argv[6]);
		char md5[MD5_LEN + 1];
		char cmd5[MD5_LEN + 1];
		char buffer[MAX_DATA];
		strncpy (buffer, argv[3], sizeof (buffer));
		md5_calc ((unsigned char *) md5, (unsigned char *) buffer,
			  strlen (buffer));
		for (i = 0; i < MD5_LEN; i += 2)
			sprintf (cmd5 + i, "%02x",
				 (unsigned char) md5[i / 2]);
		ret = db_add (userid, cmd5, argv[4], bitrate, issave);
		db_end ();
		exit (ret);
	} else if (argc >= 3 && strcmp (argv[1], "-del") == 0)
	{
		ret = userid = atoi (argv[2]);
		db_del (userid);
		db_end ();
		exit (ret);
	} else if (argc >= 2 && strcmp (argv[1], "-list") == 0)
	{
		ret = db_list ();
		db_end ();
		exit (ret);
	}
	fprintf (stderr,
		 "Usage:%s -add userid password channelname bitrate issave\n\t%s -del userid\n\t%s -list\n\n", argv[0], argv[0], argv[0]);
	db_end ();
	return 0;
}
